#                ,            
#   _  _/_ __    __   _   _  
#  /_)_(__/ (__(_/ (_(_/_/_)_
#                   .-/      
#                  (_/       
#
#  http://stringswiki.com
#  Understanding the simplicity
#  Copyright 2009, Asbjorn Enge. All rights reserved.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
#  MA  02111-1307  USA
#
#  (C) 2009
"""

	request.py - Request handling


"""
__author__  = 'Asbjorn Enge <asbjorn@hanafjedle.net>'

import webob

class Request(webob.Request):
	
	def redirect(self, url, permanently=False):
		#self.resp.clear()
		if permanently:
			self.resp.status_int = 301
		else:
			self.resp.status_int = 302
		self.resp.headers['Location'] = url

def static_controller(file_info):
	""" Controller for static content
	"""
	def replacement(environ, start_response):
		req = Request(environ)
		f = open(file_info['fullpath'], 'r')
		# TODO: Don't read whole file!? Have max bytes param
		content = f.read()
		f.close()
		resp = webob.Response(body=content)
		resp.content_type = file_info['mtype']
		return resp(environ, start_response)
	return replacement

def tune_controller(cls):
	""" Controller to handle get/post actions
	"""
	def replacement(environ, start_response):
		req = Request(environ)
		req.resp = resp = webob.Response(charset='utf-8')
		try:
			instance = cls(req, **req.urlvars)
			action = req.urlvars.get('action')
			if not action:
				action = req.method.lower()
			try:
				method = getattr(instance, action)
			except AttributeError:
				raise webob.exc.HTTPNotFound("No action for %s" % action)
			resp_body = method()
			if isinstance(resp_body, basestring):
				resp.unicode_body = resp_body
		except webob.exc.HTTPException, e:
			resp = e
		return resp(environ, start_response)
	return replacement
